package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dtos.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.service.ArticleSearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    ApUserSearchServiceImpl apUserSearchService;

    @Autowired
    BehaviorFeign behaviorFeign;


    @Override
    public ResponseResult search(UserSearchDto dto) {
        List<Map> arrayList = new ArrayList<Map>();
        try {
            if (dto==null || StringUtils.isBlank(dto.getSearchWords()) || dto.getMinBehotTime()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //调用线程池中初始化好的线程，去执行保存方法
            //获取登录用户
            ApUser user = AppThreadLocalUtils.getUser();
            if (user==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }

            //查用户行为
            ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (apBehaviorEntry==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            apUserSearchService.insert(apBehaviorEntry.getEntryId(),dto.getSearchWords());




            //读取索引库数据
            SearchRequest searchRequest = new SearchRequest("app_info_article");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //组合多条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            //关键字匹配查询
            QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title").field("content").defaultOperator(Operator.OR);

            boolQueryBuilder.must(queryStringQueryBuilder);

            //时间区间查询
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime")
                    .lt(dto.getMinBehotTime());
            boolQueryBuilder.filter(rangeQueryBuilder);


            searchSourceBuilder.query(boolQueryBuilder);
            //按发布时间倒序排序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);
            //设置分页
            searchSourceBuilder.from(dto.getPageNum());
            searchSourceBuilder.size(dto.getPageSize());


            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);



            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits) {
                String source = hit.getSourceAsString();  //json串
                Map map = JSON.parseObject(source, Map.class);  //json串转字符串
                arrayList.add(map);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.okResult(arrayList);
    }
}
